package com.gxks.lhs.controller.admin;

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobContainerClientBuilder;
import com.gxks.lhs.constants.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
public class FileUploadController {

    @Value("${azure.containerUrl}")
    private String containerUrl;
    @Value("${azure.sasToken}")
    private String sasToken;
    @Value("${azure.containerName}")
    private String containerName;

    @PostMapping("/uploadblob")
    public R handleFileUpload(MultipartFile file) throws IOException {

        log.warn("开始上传");
        log.warn(containerUrl);
        log.warn(sasToken);
        BlobContainerClient blobContainerClient = new BlobContainerClientBuilder()
                .endpoint(containerUrl)
                .sasToken(sasToken)
                .containerName(containerName)
                .buildClient();

        String fileName = generateUniqueFileName(file.getOriginalFilename());
        BlobClient blobClient = blobContainerClient.getBlobClient(fileName);
        try (InputStream inputStream = file.getInputStream()) {
            blobClient.upload(inputStream, file.getSize());
        }
        return R.success().setData(containerUrl + "/" + containerName + "/" + fileName);
    }

    private String generateUniqueFileName(String originalFilename) {
        String extension = FilenameUtils.getExtension(originalFilename);
        String baseName = UUID.randomUUID().toString();
        return baseName + '.' + extension;
    }
}

